package fun.linze.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/v1/files")
public class FileController {

    @Value("${file.upload.path.wallpaper}")
    private String wallpaperPath;

    @Value("${file.upload.path.avatar}")
    private String avatarPath;


    /// 壁纸处理


    /// 壁纸上传
    @PostMapping("/wallpapers")
    public ResponseEntity<String> uploadWallpaper(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Upload failed, please select a file.");
        }

        String fileName = file.getOriginalFilename();
        File dest = new File(wallpaperPath + fileName);
        try {
            dest.getParentFile().mkdirs();
            file.transferTo(dest);
            return ResponseEntity.ok("Upload successful");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Upload failed.");
        }
    }

    /// 头像上传
    @PostMapping("/avatars")
    public ResponseEntity<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Upload failed, please select a file.");
        }

        String fileName = file.getOriginalFilename();
        File dest = new File(avatarPath + fileName);
        try {
            dest.getParentFile().mkdirs();
            file.transferTo(dest);
            return ResponseEntity.ok("Upload successful");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Upload failed.");
        }
    }
}
